package com.passer.toolbox.tfile.command.filededuplication;

import com.passer.toolbox.common.core.util.StringUtils;
import com.passer.toolbox.common.util.file.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 重复文件检查
 */
public class FileDeduplication {
    public void starter(String filePath) {
        File file = new File(StringUtils.isEmpty(filePath) ? "." : filePath);
        if (!file.exists()) {
            System.out.println("目录不存在");
            return;
        }

        System.out.println("文件比较中...");

        Map<String, List<String>> map;
        try {
            map = getRepetitiveFiles(file);
        } catch (IOException e) {
            System.out.println("文件查重失败：" + e.getMessage());
            return;
        }
        if (map.isEmpty()) {
            System.out.println(file.getAbsoluteFile()+"：无重复文件");
            return;
        }
        for (Map.Entry<String, List<String>> listEntry : map.entrySet()) {
            List<String> value = listEntry.getValue();
            System.out.println(listEntry.getKey());
            for (String fileName : value) {
                System.out.println(listEntry.getKey() + "：" + fileName);
            }
        }

    }

    public Map<String, List<String>> getRepetitiveFiles(File folder) throws IOException {
        Map<String, List<String>> md5Map = FileUtils.classifyFileByMD5(folder);
        Map<String, List<String>> repetitiveFiles = new HashMap<>();
        for (Map.Entry<String, List<String>> fileMd5 : md5Map.entrySet()) {
            List<String> value = fileMd5.getValue();
            if (value.size() > 1) {
                repetitiveFiles.put(fileMd5.getKey(), value);
            }
        }
        return repetitiveFiles;
    }
}
